import {messages} from "share/common";
import React, { Component } from "react";
import { Icon, Modal, Menu, Radio, Row, Col, Affix, Popover, Collapse } from "antd";
import Condition from "components/condition";
import ColumnLayout from "components/template/slide-document/column-layout";
import { menuList, menuContent } from "./dataSource"

const Panel = Collapse.Panel;
const { If, Else } = Condition;

const { ColumnLayoutLeft, ColumnLayoutRight } = ColumnLayout;

class AuditTipsDetail extends Component {

  state = {
    pageKey: this.props.pageKey || 'scan',
    radioKey: this.props.radioKey || 'scan_page',
    anchorId: null,
    collapseActiveKey: this.props.collapseKey || [],
  };

  componentDidMount() {
    if (window.addEventListener) {
      window.addEventListener('keyup', this.handleKeyUp);
    } else {
      window.attachEvent('onkeyup', this.handleKeyUp);
    }
  }

  componentWillUnmount() {
    if (window.addEventListener) {
      window.removeEventListener('keyup', this.handleKeyUp);
    } else {
      window.detachEvent('onkeyup', this.handleKeyUp);
    }
  }

  handleKeyUp = e => {
    e.stopPropagation();
    let { pageKey } = this.state;
    const pageIndex = menuList.findIndex(item => item.key === pageKey);
    const activeItem = document.getElementsByClassName('ant-menu-item-active')[0];
    activeItem && (activeItem.className = 'ant-menu-item');
    switch(e.keyCode){
      // UP
      case 38:
        if (pageIndex > 0) {
          this.changeCurrentPage(menuList[pageIndex - 1].key);
        }
        break;
      // DOWN
      case 40:
        if (pageIndex < menuList.length - 1) {
          this.changeCurrentPage(menuList[pageIndex + 1].key);
        }
        break;
    }
  };

  changeCurrentPage = key => {
    let { pageKey } = this.state;
    key !== pageKey && this.setState({
      pageKey: key,
      radioKey: menuContent[key][0].value,
      collapseActiveKey: [],
      anchorId: null
    }, () => {
      this.container && (this.container.scrollTop = 0);
    })
  };

  getAnchorList = list => {
    const anchorOptions = [];
    list && list.map(item => {
      item.id = item.id || item.key;
      item.anchorTitle && anchorOptions.push(item);
    });
    return anchorOptions;
  };

  renderTitle = () => (
    <div className="audit-tips-detail-header">
      <Icon className="audit-tips-detail-header-back" type='left' onClick={this.props.onCancel} />
      <span className="audit-tips-detail-header-title">{messages('expense-14.key138')/*实用小技巧*/}</span>
      <span className="audit-tips-detail-header-tip">{messages('expense-14.key139')/*点击键盘上下可以切换小技巧介绍*/}</span>
    </div>
  );

  renderLeftContent = () => {
    const { pageKey } = this.state;
    return (
      <div className="audit-tips-detail-left">
        <Menu
          mode="inline"
          selectedKeys={[pageKey]}
          onClick={e => this.changeCurrentPage(e.key)}
        >
          {menuList.map(item => (
            <Menu.Item key={item.key}>{item.name}</Menu.Item>
          ))}
        </Menu>
      </div>
    )
  };

  renderRightContent = () => {
    const { pageKey, radioKey, anchorId, collapseActiveKey } = this.state;
    const radioOptions = menuContent[pageKey];
    // 解决有展开操作的tab页切换时，初始状态为上一个tab展开状态的问题
    const showContent = radioKey ? radioOptions.filter(item => item.value === radioKey)[0] :
      radioOptions[0].category ? [] : radioOptions[0];
    const menuDetail = menuList.filter(item => item.key === pageKey)[0];
    return (
      <div className="audit-tips-detail-right" ref={node => this.container = node} onScroll={this.onPageScroll}>
        <div className="audit-tips-detail-right-header">{menuDetail.title}</div>
        <If value={menuDetail.extra}>
          <div className="audit-tips-detail-right-extra">{menuDetail.extra}</div>
        </If>
        <If value={radioOptions[0].value}>
          <Radio.Group
            value={radioKey}
            onChange={e => this.setState({ radioKey: '' }, () => this.setState({ radioKey: e.target.value }))}
          >
            {radioOptions.map(item => (
              <Radio.Button value={item.value}>{item.label}</Radio.Button>
            ))}
          </Radio.Group>
        </If>
        <If value={showContent.title}>
          <div style={{ marginBottom: 8 }}>{showContent.title}</div>
        </If>
        <div ref={node => this.box = node}>
          <Row className="audit-tips-detail-right-box">
            <Col span={20} className="audit-tips-detail-right-content">
              {this.renderImage(showContent.images)}
              {showContent.category && showContent.category.map(item => (
                <div className="audit-tips-detail-right-collapse">
                  <div className="audit-tips-detail-right-collapse-top">
                    {this.renderPanelHeader(item)}
                  </div>
                  <div className={this.classNames(['audit-tips-detail-right-collapse-content', {
                    'expand': collapseActiveKey.includes(item.key)
                  }])}>
                    {this.renderImage(item.images)}
                  </div>
                </div>
              ))}
            </Col>
            <Col span={4} className="audit-tips-detail-right-anchor">
              <Affix target={() => this.container}>
                <div style={{ borderLeft: '2px solid #F5F5F5' }}>
                  {this.getAnchorList(showContent.images || showContent.category).map(item => (
                    <div
                      className={`audit-tips-detail-right-anchor-item ${item.id === anchorId ? 'active' : ''}`}
                      onClick={() => {
                        document.getElementById(item.id) && document.getElementById(item.id).scrollIntoView({behavior: 'smooth'});
                        this.setState({ anchorId: item.id });
                      }}
                    >
                      {item.anchorTitle}
                    </div>
                  ))}
                </div>
              </Affix>
            </Col>
          </Row>
        </div>
      </div>
    )
  };

  renderImage = images => {
    return images ? images.map(item => (
      <div className="audit-tips-detail-right-image">
        <Condition>
          <If value={item.id}>
            <img id={item.id} src={item.src} alt="" />
          </If>
          <Else>
            <img src={item.src} alt="" />
          </Else>
        </Condition>
        {item.operateList && item.operateList.map(operateItem => (
          <Condition>
            <If value={operateItem.content}>
              <Popover content={operateItem.content} {...(operateItem.props || {})}>
                <span className="audit-tips-detail-right-image-text" style={operateItem.style} />
              </Popover>
            </If>
            <Else>
              <span
                className="audit-tips-detail-right-image-text"
                style={operateItem.style}
                onClick={() => operateItem.onClick && operateItem.onClick(this)}
              />
            </Else>
          </Condition>
        ))}
      </div>
    )) : null
  };

  renderPanelHeader = ({ content, key }) => {
    const { collapseActiveKey } = this.state;
    return (
      <Row>
        <Col span={20}>
          {content}
        </Col>
        <Col span={4}>
          <div
            className="audit-tips-detail-right-collapse-operate"
            onClick={() => this.handleChangeCollapse(key)}
          >
            {messages('expense-14.key140')/*如何操作*/}
            <Icon
              type="down"
              style={{
                transitionDuration: '.7s',
                transform: collapseActiveKey.includes(key) ? 'rotate(-180deg)' : 'unset'
              }}
            />
          </div>
        </Col>
      </Row>
    )
  };

  handleChangeCollapse = key => {
    let { collapseActiveKey } = this.state;
    if (collapseActiveKey.includes(key)) {
      collapseActiveKey.delete(key);
    } else {
      collapseActiveKey.push(key);
    }
    this.setState({ collapseActiveKey })
  };

  onPageScroll = () => {
    let scrollTop = this.container && this.container.scrollTop;
    let offsetTop = this.box && this.box.offsetTop;
    if (scrollTop && offsetTop) {
      this.setState({
        isAnchorFixed: scrollTop >= offsetTop
      })
    }
  };

  render() {
    const { visible, onCancel } = this.props;
    return (
      <Modal
        visible={visible}
        className="audit-tips-detail"
        title={this.renderTitle()}
        width='100%'
        footer={null}
        mask={false}
        zIndex={1001}
        onCancel={onCancel}
      >
        <ColumnLayout leftWidth={200}>
          <ColumnLayoutLeft>{this.renderLeftContent()}</ColumnLayoutLeft>
          <ColumnLayoutRight>{this.renderRightContent()}</ColumnLayoutRight>
        </ColumnLayout>
      </Modal>
    );
  }
}

export default AuditTipsDetail;
